const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const pool = require('../../pool.js');
const upload = express.Router();
// 上传图片
upload.post('/upload', multer({
    // 此路径是绝对路径，在不同的文件夹要调整对应的位置
    dest: `${__dirname}/commodity/`
}).array('file'), (req, res) => {
    let imgUrl = '';
    for (const key of req.files) {
        let oldname = key.path;
        let newname = key.path + path.parse(key.originalname).ext;
        fs.renameSync(oldname, newname);
        imgUrl = newname.split('\\').pop();
    }
    res.send(imgUrl);
});
// 图片和信息
upload.post('/upinfo', (req, res) => {
    let { title, commodity, price, inventory, img, type, kind, shopId } = req.body;
    pool.query('insert into goods set title=?,commodity=?,price=?,inventory=?,img=?,type=?,kind=?,shopId=?', [title, commodity, price, inventory, img, type, kind, shopId], (err, r) => {
        if (err) {
            throw err;
        }
        res.send(r);
    })
})

// 删除图片
upload.delete('/delimg', (req, res) => {
    let img = req.query.img;
    console.log(__dirname);
    fs.unlinkSync(`${__dirname}/commodity/${img}`);
})
module.exports = upload;